package com.kjtpay.design_pattern.singleton;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.kjtpay.design_pattern.R;
import com.kjtpay.design_pattern.adapter.AdapterActivity;

public class SingletonActivity extends AppCompatActivity {

    public static void launch(Context context) {
        if (null != context) {
            Intent intent = new Intent();
            intent.setClass(context, SingletonActivity.class);
            if (!(context instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            context.startActivity(intent);
        }
    }

    TextView checkTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_singleton);
        setTitle("单例模式");

        checkTextView = findViewById(R.id.textViewCheck);
    }

    public void onLazyButtonClick(View view) {
        LazySingleton lazySingleton1 = LazySingleton.getInstance();
        LazySingleton lazySingleton2 = LazySingleton.getInstance();
        checkSingleton(lazySingleton1, lazySingleton2);
    }

    public void onEagerButtonClick(View view) {
        EagerSingleton eagerSingleton1 = EagerSingleton.getInstance();
        EagerSingleton eagerSingleton2 = EagerSingleton.getInstance();
        checkSingleton(eagerSingleton1, eagerSingleton2);
    }

    public void onDoubleCheckButtonClick(View view) {
        DoubleCheckSingleton doubleCheckSingleton1 = DoubleCheckSingleton.getInstance();
        DoubleCheckSingleton doubleCheckSingleton2 = DoubleCheckSingleton.getInstance();
        checkSingleton(doubleCheckSingleton1, doubleCheckSingleton2);
    }

    public void onNestedClassButtonClick(View view) {
        StaticNestedClassSingleton staticNestedClassSingleton1 = StaticNestedClassSingleton.getInstance();
        StaticNestedClassSingleton staticNestedClassSingleton2 = StaticNestedClassSingleton.getInstance();
        checkSingleton(staticNestedClassSingleton1, staticNestedClassSingleton2);
    }

    private void checkSingleton(Object object1, Object object2) {
        String message = "";
        if (object1 == object2) {
            message = "对象object1:" + object1 + "\n"
                    + "对象object2：" + object2 + "\n"
                    + "是相同的实例";
        } else {
            message = "对象object1:" + object1 + "\n"
                    + "对象object2：" + object2 + "\n"
                    + "是不同的实例";
        }
        checkTextView.setText(message);
    }
}